package cn.icanci.loopstack.plugin.dalgen.util;

import cn.icanci.loopstack.plugin.dalgen.config.GlobalConfig;
import cn.icanci.loopstack.plugin.dalgen.model.ConfigurationInfoVO;

import java.sql.Connection;
import java.sql.DriverManager;

/**
 * DBUtil DB连接
 *
 * @author icanci
 * @since 1.0 Created in 2022/05/13 18:14
 */
public class DBUtil {

    private volatile static Connection conn = null;

    static {
        try {
            Class.forName(GlobalConfig.getGobleConfig().getDriver());
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }

    private static Connection produceConnection() throws Exception {
        ConfigurationInfoVO config = GlobalConfig.getGobleConfig();
        return DriverManager.getConnection(config.getConnectUrl(), config.getLoginName(), config.getPassword());
    }

    /***
     * 获取数据库连接,双重校验保证线程安全
     */
    public static Connection getConnection() {
        try {
            if (null == conn) {
                synchronized (DBUtil.class) {
                    if (null == conn) {
                        long start = System.currentTimeMillis();
                        conn = produceConnection();
                        System.out.println("Connection is ready. consume time is: " + (System.currentTimeMillis() - start) + "ms");
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return conn;
    }
}
